<template>
   <div class="app-container">
      <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true" label-width="82px">
         <el-form-item label="区域名称" prop="areaId">
            <!-- <el-select v-model="queryParams.areaId" placeholder="请选择区域名称" style="width: 240px" clearable
               @keyup.enter="handleQuery">
               <el-option v-for="item in areaOptions" :key="item.areaCode" :label="item.name" :value="item.areaCode" />
            </el-select> -->
            <el-tree-select v-model="queryParams.areaId" :data="areaOptions" clearable style="width: 240px" @change="areaChange" filterable
                  :props="{ label: 'name', children: 'areaList' }" node-key="areaCode" :check-strictly="true"
                  @keyup.enter="handleQuery"
                  placeholder="请选择区域" :render-after-expand="false" default-expand-all  controls-position="right" />
         </el-form-item>
         <el-form-item label="预警等级" prop="warningLevel">
            <el-select v-model="queryParams.warningLevel" clearable placeholder="请选择预警等级" style="width: 240px"
               @keyup.enter="handleQuery">
               <el-option v-for="item in warningLevelOptions" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
         </el-form-item>
         <el-form-item label="预警方式" prop="warningWay">
            <el-select v-model="queryParams.warningWay" clearable placeholder="请选择预警方式" style="width: 240px"
               @keyup.enter="handleQuery">
               <el-option v-for="item in warningWaysOptions" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
         </el-form-item>
         <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
         </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
         <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['contact:add']">新增</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
               v-hasPermi="['contact:edit']">修改</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
               v-hasPermi="['contact:remove']">删除</el-button>
         </el-col>
         <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
      <!-- 表格数据 -->
      <el-table v-loading="loading" :data="roleList" @selection-change="handleSelectionChange">
         <el-table-column type="selection" width="55" align="center" />
         <el-table-column label="区域名称" align="center" prop="areaName" width="120" />
         <el-table-column label="预警类型" align="center" prop="warningType" width="150" :show-overflow-tooltip="true" >
            <template #default="scope">
               {{ sys_warning_type.find(item => item.value == scope.row.warningType)?.label }}
            </template>
         </el-table-column>
         <el-table-column label="预警等级" align="center" prop="warningLevel" :show-overflow-tooltip="true" >
            <template #default="scope">
               <!-- {{ warningLevelOptions.find(item => item.id == scope.row.warningLevel)?.name }} -->
               <el-tag v-if="scope.row.warningLevel==0" type="info">无</el-tag>
               <el-tag v-if="scope.row.warningLevel==1">低</el-tag>
               <el-tag  v-if="scope.row.warningLevel==2" class="ml-2" type="warning">中</el-tag>
               <el-tag  v-if="scope.row.warningLevel==3" class="ml-2" type="danger">高</el-tag>
            </template>
         </el-table-column>
         <el-table-column label="月份" align="center" prop="month" :show-overflow-tooltip="true" />
         <el-table-column label="最小温度（°C）" width="120" align="center" prop="minTemperature" :show-overflow-tooltip="true" />
         <el-table-column label="最大温度（°C）" width="120" align="center" prop="maxTemperature" :show-overflow-tooltip="true" />
         <el-table-column label="预警方式" align="center" prop="warningWays" width="200" :show-overflow-tooltip="true">
            <template #default="scope">
               {{getWarningWays(scope.row.warningWays)}}
            </template>
         </el-table-column>
         <el-table-column label="联系人1" align="center" prop="email" :show-overflow-tooltip="true" >
            <template #default="scope">
               {{ scope.row.warningContacts.split(',')[0] }}
            </template>
         </el-table-column>
         <el-table-column label="联系人2" align="center" prop="email" :show-overflow-tooltip="true" >
            <template #default="scope">
               {{ scope.row.warningContacts.split(',')[1]||'' }}
            </template>
         </el-table-column>
         <el-table-column label="联系人3" align="center" prop="email" :show-overflow-tooltip="true" >
            <template #default="scope">
               {{ scope.row.warningContacts.split(',')[2] || '' }}
            </template>
         </el-table-column>
         <el-table-column label="联系人4" align="center" prop="email" :show-overflow-tooltip="true" >
            <template #default="scope">
               {{ scope.row.warningContacts.split(',')[3] }}
            </template>
         </el-table-column>
         <el-table-column label="联系人5" align="center" prop="email" :show-overflow-tooltip="true" >
            <template #default="scope">
               {{ scope.row.warningContacts.split(',')[4] }}
            </template>
         </el-table-column>
         <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="240">
            <template #default="scope">
               <el-tooltip content="修改" placement="top">
                  <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['contact:edit']"></el-button>
               </el-tooltip>
               <el-tooltip content="删除" placement="top">
                  <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['contact:remove']"></el-button>
               </el-tooltip>
            </template>
         </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
         v-model:limit="queryParams.pageSize" @pagination="getList" />
      <!-- 添加或修改联系人配置对话框 -->
      <el-dialog :inline="true"  :title="title" v-model="open" @close="visible = false" @click="visible = false"
         width="500px" append-to-body>
         <el-form ref="roleRef"  :model="form" :rules="rules" label-width="140px" size="mini">
            <el-form-item label="区域名称" prop="areaId">
               <el-tree-select v-model="form.areaId" :data="areaOptions" clearable @change="areaChange" filterable
                  :props="{ label: 'name', children: 'areaList' }" node-key="areaCode" :check-strictly="true"
                  placeholder="请选择区域" :render-after-expand="false" default-expand-all controls-position="right" />
               <!-- <el-select  v-model="form.areaId" @change="areaChange" placeholder="请选择区域名称" controls-position="right">
                  <el-option v-for="item in areaOptions" :key="item.areaCode" :label="item.name" :value="item.areaCode" />
               </el-select> -->
            </el-form-item>
            <el-form-item label="摄像头" prop="cameraIndexCodeBefor">
               <el-select
                  v-loading="cameraLoading"
                  v-model="form.cameraIndexCodeBefor"
                  placeholder="请选择摄像头"
                  :disabled="!form.areaId"
                  @change="cameraChange"
                  multiple
               >
                  <el-option
                  v-for="item in deviceOptions"
                  :key="item.id"
                  :label="item.deviceName"
                  :value="item.id"
                  />
               </el-select>
            </el-form-item>
            <el-form-item label="月份" prop="monthBefor">
               <el-select
                  v-model="form.monthBefor"
                  v-loading="monthLoading"
                  multiple
                  placeholder="请选择月份"
                  :disabled="!form.areaId"
                  @change="changeMonthBefor"
               >
               <template #header>
                  <el-checkbox
                  v-model="checkAll"
                  :indeterminate="indeterminate"
                  @change="handleCheckAll"
                  >
                  全选
                  </el-checkbox>
               </template>
                  <el-option
                  v-for="item in monthOptions"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                  :disabled="item.disabled"
                  />
               </el-select>
            </el-form-item>
            <el-form-item label="预警类型" prop="warningType">
               <el-select v-model="form.warningType" placeholder="请选择预警类型" controls-position="right">
                  <el-option v-for="item in sys_warning_type" :key="item.value" :label="item.label" :value="item.value" />
               </el-select>
            </el-form-item>
            <el-form-item label="预警等级" prop="warningLevel">
               <el-select v-model="form.warningLevel" placeholder="请选择预警等级" controls-position="right">
                  <el-option v-for="item in warningLevelOptions" :key="item.id" :label="item.name" :value="item.id" />
               </el-select>
            </el-form-item>
            <el-form-item label="温度最小值（°C）" prop="minTemperature" size="mini">
               <el-input v-model="form.minTemperature" controls-position="right" />
            </el-form-item>
            <el-form-item label="温度最大值（°C）" prop="maxTemperature" size="mini">
               <el-input v-model="form.maxTemperature" controls-position="right" />
            </el-form-item>
            <el-form-item label="通知时间间隔" prop="timeInterval" size="mini">
               <el-input v-model="form.timeInterval" placeholder="请输入通知时间间隔" controls-position="right" >
                  <template #append>分钟</template>
               </el-input>
            </el-form-item>
            <el-form-item label="预警方式" prop="warningWaysBefor">
               <el-checkbox-group v-model="form.warningWaysBefor">
                  <el-checkbox label="0">电话</el-checkbox>
                  <el-checkbox label="1">钉钉</el-checkbox>
                  <el-checkbox label="2">邮箱</el-checkbox>
                  <el-checkbox label="3">短信</el-checkbox>
               </el-checkbox-group>
            </el-form-item>
            <el-form-item label="联系人1" prop="warningContactsId1">
               <el-select filterable v-model="form.warningContactsId1" placeholder="请选择联系人1" controls-position="right">
                  <el-option  v-for="item in idOptions" :key="item.id" :label="item.contactsName+(item.phoneNumber?item.phoneNumber:'')" :value="item.id+','+item.contactsName+','+item.phoneNumber" />
               </el-select>
            </el-form-item>
            <el-form-item label="联系人2" prop="warningContactsId2">
               <el-select filterable :clearable="!form.warningContactsId3" v-model="form.warningContactsId2" :disabled="!form.warningContactsId1"  placeholder="请选择联系人2" controls-position="right">
                  <el-option  v-for="item in idOptions" :key="item.id" :label="item.contactsName+(item.phoneNumber?item.phoneNumber:'')" :value="item.id+','+item.contactsName+','+item.phoneNumber" />
               </el-select>
            </el-form-item>
            <el-form-item label="联系人3" prop="warningContactsId3">
               <el-select filterable :clearable="!form.warningContactsId4" v-model="form.warningContactsId3" :disabled="!form.warningContactsId2" placeholder="请选择联系人3" controls-position="right">
                  <el-option  v-for="item in idOptions" :key="item.id" :label="item.contactsName+(item.phoneNumber?item.phoneNumber:'')" :value="item.id+','+item.contactsName+','+item.phoneNumber" />
               </el-select>
            </el-form-item>
            <el-form-item label="联系人4" prop="warningContactsId4">
               <el-select filterable :clearable="!form.warningContactsId5" v-model="form.warningContactsId4" :disabled="!form.warningContactsId3" placeholder="请选择联系人4" controls-position="right">
                  <el-option  v-for="item in idOptions" :key="item.id" :label="item.contactsName+(item.phoneNumber?item.phoneNumber:'')" :value="item.id+','+item.contactsName+','+item.phoneNumber" />
               </el-select>
            </el-form-item>
            <el-form-item label="联系人5" prop="warningContactsId5">
               <el-select filterable clearable v-model="form.warningContactsId5" :disabled="!form.warningContactsId4" placeholder="请选择联系人5" controls-position="right">
                  <el-option  v-for="item in idOptions" :key="item.id" :label="item.contactsName+(item.phoneNumber?item.phoneNumber:'')" :value="item.id+','+item.contactsName+','+item.phoneNumber" />
               </el-select>
            </el-form-item>
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitForm">确 定</el-button>
               <el-button @click="cancel">取 消</el-button>
            </div>
         </template>
      </el-dialog>
   </div>
</template>

<script setup name="rule">
import { pageUration, getUration, addUration,getMonth, updateUration, delUration } from "@/api/alarm/rule";
import {listContact} from '@/api/alarm/contact'
import {ref,reactive,watch } from "vue";
import {treeArea} from '@/api/area.js'
import {list} from '@/api/device.js'
const router = useRouter();
const { proxy } = getCurrentInstance();
const { sys_warning_type } = proxy.useDict("sys_warning_type");
const cameraLoading = ref(false)
const monthLoading = ref(false)
const deviceOptions = ref([])

const checkAll = ref(false)
const indeterminate = ref(false)


const handleCheckAll = (val) => {
  indeterminate.value = false
  if (val) {
   form.value.monthBefor = monthOptions.value.map(_=>{
      if(!_.disabled){
         return _.value
      }
   }).filter(_=> _)
  } else {
   form.value.monthBefor = []
  }
}
const changeMonthBefor = (val) =>{
   if (val.length === 0) {
    checkAll.value = false
    indeterminate.value = false
  } else if (val.length === monthOptions.value.length) {
    checkAll.value = true
    indeterminate.value = false
  } else {
    indeterminate.value = true
  }
}
//获取预警方式
const getWarningWays = (str)=>{
   const arr = str.split(',')
   const options = [
      {name:'电话',value:'0'},
      {name:'钉钉',value:'1'},
      {name:'邮箱',value:'2'},
      {name:'短信',value:'3'},
   ]
   let newStr=  []
   arr.forEach(el=>{
      options.forEach(el2=>{
         if(el==el2.value){
            newStr.push(el2.name) 
         }
      })
   })
   return newStr.join(',')
}

const areaChange = (e)=>{
   cameraLoading.value = true
   // resetMonthOptions();
   //获取摄像头列表
   list({areaCode:e}).then(res=>{
      deviceOptions.value = res.data
   })
   //清空摄像头和月份
   form.value.cameraIndexCodeBefor = null
   form.value.monthBefor = null
   checkAll.value = false
    indeterminate.value = false
   cameraLoading.value = false
}
const disabledMouth = ref(null);

const cameraChange = (e)=>{
   monthLoading.value = true
   //先重新获取月份列表防止上次禁用的切换后还是禁用
   // form.value.monthBefor = null
   //禁用月份
   // getMonth(e).then(res=>{
   //    disabledMouth.value = res.data
   //    res.data.forEach(item=>{
   //       monthOptions.value.forEach(item2=>{
   //          if(item==item2.value){
   //             item2.disabled = true
   //          }
   //       })
   //    })
   // })
   monthLoading.value = false
}
function formatNumber(num) {
    return String(num).padStart(2, '0');
}

const resetMonthOptions = ()=>{
   monthOptions.value = Array.from({ length: 12 }, (_, index) => {
    // 计算月份数字
    const monthNumber = formatNumber(index + 1);
    // 构建月份名称
    const monthName = `${monthNumber}月`;
    // 返回包含月份信息的对象
    return {
        name: monthName,
        value: monthNumber,
        disabled: false
    };
});
}

let monthOptions = ref();

const roleList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const menuExpand = ref(false);
const menuNodeAll = ref(false);
const deptExpand = ref(true);
const menuRef = ref(null);
const idOptions = ref([])
const data = reactive({
   form: {
   },
   queryParams: {
      pageNum: 1,
      pageSize: 10,
      areaId: undefined,
      warningLevel: undefined,
      warningWay: undefined
   },
   rules: {
      areaId: [{ required: true, message: "区域名称不能为空", trigger: "blur" }],
      warningType: [{ required: true, message: "预警类型不能为空", trigger: "blur" }],
      warningWaysBefor: [{ required: true, message: "预警方式不能为空", trigger: "blur" }],
      minTemperature: [{ required: true, message: "温度最小值不能为空", trigger: "blur" }],
      maxTemperature: [{ required: true, message: "温度最大值不能为空", trigger: "blur" }],
      monthBefor: [{ required: true, message: "月份不能为空", trigger: "blur" }],
      warningContactsId1: [{ required: true, message: "月份不能为空", trigger: "blur" }],
      cameraIndexCodeBefor: [{ required: true, message: "摄像头不能为空", trigger: "blur" }],
      timeInterval: [{ required: true, message: "通知时间间隔不能为空", trigger: "blur" },{ pattern: /^[1-9]\d*$/, message: "格式不正确", trigger: "blur" }],
   },
});
const warningLevelOptions = ref([
   { id: 0, name: '无' },
   { id: 1, name: '低' },
   { id: 2, name: '中' },
   { id: 3, name: '高' },
])
function createTreeSearcher(tree) {
  const cache = new Map();
  
  // 构建缓存
  function buildCache(node) {
    if (node.areaCode) cache.set(node.areaCode, node.name);
    if (node.areaList) node.areaList.forEach(buildCache);
  }
  
  if (Array.isArray(tree)) {
    tree.forEach(buildCache);
  } else {
    buildCache(tree);
  }

  return (areaCode) => cache.get(areaCode);
}
const warningWaysOptions = ref([
   { id: '0', name: '电话' },
   { id: '1', name: '钉钉' },
   { id: '2', name: '邮箱' },
   { id: '3', name: '短信' },
])
const { queryParams, form, rules } = toRefs(data);
/** 查询列表 */
function getList() {
   loading.value = true;
   pageUration(proxy.addDateRange(queryParams.value)).then(response => {
      roleList.value = response?.data?.rows;
      total.value = response?.data?.total;
      loading.value = false;
   });
}

/** 搜索按钮操作 */
function handleQuery() {
   queryParams.value.pageNum = 1;
   getList();
}

/** 重置按钮操作 */
function resetQuery() {
   dateRange.value = [];
   proxy.resetForm("queryRef");
   handleQuery();
}

/** 删除按钮操作 */
function handleDelete(row) {
   const Ids = row.id || ids.value;
   proxy.$modal.confirm('是否确认删除规则？').then(function () {
      return delUration(Ids);
   }).then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
   }).catch(() => { });
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
   ids.value = selection.map(item => item.id);
   single.value = selection.length != 1;
   multiple.value = !selection.length;
}

const setContactsId = ()=>{
      // 将字符串分割成数组
      //id name phoneNumber
      let strs = [form.value.warningContactsId1,form.value.warningContactsId2,form.value.warningContactsId3,form.value.warningContactsId4,form.value.warningContactsId5]
      strs = strs.filter(el=> el )
      //名称
      const warningContacts = []
      //id
      const warningContactsId = []
      //电话
      const warningContactsPhone = []
      for(let i = 0 ;i<strs.length;i++){
             // 将当前字符串按逗号分割成数组
            const currentArr = strs[i].split(',');
            warningContactsId.push(currentArr[0]);
            warningContacts.push(currentArr[1]);
            warningContactsPhone.push(currentArr[2]);
      }
      form.value.warningContacts = warningContacts.join(',')
      form.value.warningContactsId = warningContactsId.join(',')
      form.value.warningContactsPhone = warningContactsPhone.join(',')
}

/** 重置新增的表单以及其他数据  */
function reset() {
   if (menuRef.value != undefined) {
      menuRef.value.setCheckedKeys([]);
   }
   menuExpand.value = false;
   menuNodeAll.value = false;
   deptExpand.value = true;
   form.value = {
      id: undefined,
      monthBefor:null
   };
   proxy.resetForm("roleRef");
}
/** 添加规则 */
function handleAdd() {
   reset();
   open.value = true;
   form.value.timeInterval  = 10
   title.value = "添加规则";
}

/** 修改规则 */
function handleUpdate(row) {
   reset();
   getUration(row.id||ids.value[0]).then((res) => {
   res.data.cameraIndexCodeBefor = res.data.cameraIndexCode.split(',')
   res.data.monthBefor = res.data.month.split(',')
   res.data.warningWaysBefor = res.data.warningWays.split(',')
   list({areaId:res.data.areaId}).then(res2=>{
      deviceOptions.value = res2.data
   })
   // resetMonthOptions();
   //处理人员参数
   res.data.warningContacts = res.data.warningContacts?.split(',') //[1,2,3,4,5]
   res.data.warningContactsId = res.data.warningContactsId?.split(',') //[2,3,4,5,6]
   res.data.warningContactsPhone = res.data.warningContactsPhone?.split(',') //[3,4,5,6,7]
   // for (let i = 0; i < res.data.warningContacts.length; i++) {
      res.data.warningContactsId1 =res.data.warningContactsId[0]? res.data.warningContactsId[0]+','+res.data.warningContacts[0]+','+res.data.warningContactsPhone[0]:''
      res.data.warningContactsId2 =res.data.warningContactsId[1]? res.data.warningContactsId[1]+','+res.data.warningContacts[1]+','+res.data.warningContactsPhone[1]: ''
      res.data.warningContactsId3 =res.data.warningContactsId[2]? res.data.warningContactsId[2]+','+res.data.warningContacts[2]+','+res.data.warningContactsPhone[2]: ''
      res.data.warningContactsId4 =res.data.warningContactsId[3]? res.data.warningContactsId[3]+','+res.data.warningContacts[3]+','+res.data.warningContactsPhone[3] : ''
      res.data.warningContactsId5 =res.data.warningContactsId[4]? res.data.warningContactsId[4]+','+res.data.warningContacts[4]+','+res.data.warningContactsPhone[4]:''
   // }
   form.value = res.data;
   form.value.warningType = form.value.warningType.toString()
   //禁用月份
   // getMonth(res.data.cameraIndexCode).then(res1=>{
   //    disabledMouth.value = res1.data
   //    res1.data?.forEach(item=>{
   //       monthOptions.value.forEach(item2=>{
   //          if((item==item2.value) && form.value.month.indexOf(item2.value)==-1){
   //             item2.disabled = true
   //          }
   //       })
   //    })
   // })
      open.value = true;
   }).catch(() => {
      form.value = row;
      open.value = true;
   })
   title.value = "告警规则修改";
}
function splitByCameraCode(original) {
  if (!Array.isArray(original.cameraIndexCode)) return [original];
  
  return original.cameraIndexCode.map(code => ({
    ...original,
    cameraIndexCode: code  // 覆盖原字段
  }));
}
/** 提交按钮 */
function submitForm() {
   proxy.$refs["roleRef"].validate(valid => {
      if (valid) {
         setContactsId();
         //提交前处理参数
         form.value.month= form.value.monthBefor.join(',')
         form.value.cameraIndexCode = form.value.cameraIndexCodeBefor.join(',')
         const name = createTreeSearcher(areaOptions.value)
         form.value.areaName = name(form.value.areaId)
         form.value.warningWays = form.value.warningWaysBefor.join(',')
         //人员数据整合
         if (form.value.id != undefined) {
            //联系人
            updateUration(form.value).then(response => {
               proxy.$modal.msgSuccess("修改成功");
               open.value = false;
               getList();
            });
         } else {
            addUration(form.value).then(response => {
               proxy.$modal.msgSuccess("新增成功");
               open.value = false;
               getList();
            });
         }
      }
   });
}

const areaOptions = ref([])
/** 获取数据 */
function getDeptTree() {
   treeArea().then(response=>{
      areaOptions.value = response?.data
   })
   listContact({status:0}).then(response=>{
      idOptions.value = response.data
   })
};
/** 取消按钮 */
function cancel() {
   open.value = false;
   reset();
}
watch(()=>{form.value.monthBefor}, (val) => {
   if(form.value.monthBefor){
      if (form.value.monthBefor.length === 0) {
    checkAll.value = false
    indeterminate.value = false
  } else if (form.value.monthBefor.length === monthOptions.value?.length) {
    checkAll.value = true
    indeterminate.value = false
  } else {
    indeterminate.value = true
  }
   }
 
},{deep:true})
resetMonthOptions();

getDeptTree();
getList();

</script>


<style scoped lang="scss">

</style>